package com.catsic.web.controllers;

import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.catsic.base.controller.BaseController;

@Controller
public class CertificateController extends BaseController {

	/**
	 * 获取证书信息
	 * @return
	 */
	@RequestMapping(value = "/getCertificate")
	@ResponseBody
	public Map<String,Object> getCertificate(HttpServletRequest request){
		X509Certificate[] certs = (X509Certificate[]) request
				.getAttribute("javax.servlet.request.X509Certificate");
		Map<String, Object> map = new HashMap<String, Object>(); 
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (null == certs) {
			map.put(RESULT, RESULT_SUCCESS);
			return map;
		}
		for (int i = 0; i < certs.length; i++) {
			Map<String, Object> map_ = new HashMap<String, Object>();
			java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) certs[i];
			java.security.Principal pSubject = cert.getSubjectDN();
			String certSubject = pSubject.getName();
			/*
			 * EMAILADDRESS=zjb, CN=zjb, OU=test, O=ynjtt, L=kunmingshi,
			 * ST=yunnansheng, C=cn 国家名称C 州省名称ST 地点名如市L 组织名称如公司单位名O 组织单位名称OU
			 * 通用名如用户姓名CN 电子邮件地址 EmailAddress
			 */
			if (StringUtils.isNotBlank(certSubject)) {
				String[] temp = certSubject.split(",");
				if (temp.length > 0) {
					String[] user = temp[0].split("=");
					map_.put("username",user[1]);
					list.add(map_);
				}
			}
		}
		map.put(CONTENT, list);
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}
}
